package com.ls.lserp.modules.trade.web;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.CollectionsUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.order.entity.AuditInfo;
import com.ls.lserp.modules.order.entity.OrderMateriel;
import com.ls.lserp.modules.trade.entity.HandBook;
import com.ls.lserp.modules.trade.service.HandBookService;

import freemarker.template.Configuration;
import groovy.util.ResourceException;

/**
 * @ClassName: HandBookController
 * @Description: 采购手册
 * 
 * @author 
 * @date 2017年3月10日 下午18:40:00
 *
 */

@Controller
@RequestMapping(value = "${adminPath}/purchase/handbook")
public class HandBookController extends BaseController{
	
	@Autowired
	// 保存 编辑 删除 方法
	private HandBookService handBookService;
	@Autowired
	Configuration freemarkerConfiguration;
	
	@ModelAttribute
	public HandBook get(@RequestParam(required=false) String id) {
		
		// 判断id是否为空
		if (StringUtils.isNotBlank(id)){
			
			// 执行查询语句 查询基本信息
			return handBookService.get(Long.parseLong(id));
		}else{
			
			// 若为空，实例化
			return new HandBook();
		}
	}
	
	/**
	 * @Title: 画面跳转用
	 * @return url
	 */
	@RequiresPermissions("purchase:handbook:view")
	@RequestMapping(value = { "" })
	public String list(Model model) {
		// 画面跳转
		return "modules/trade/handBook";
	}

	/**
	 * @Title: 画面检索
	 * @Description: 查询页面
	 * @param handBook
	 * @param request
	 * @param response
	 * @param model
	 * @return searchList
	 * @throws Exception
	 */
	@RequiresPermissions("purchase:handbook:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(HandBook handBook, HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "handbook");
		// 拼接字符串供分页使用
		StringBuilder searchParam = new StringBuilder();
		// 采购
		searchParam.append("&handbookNo=");
		searchParam.append(handBook.getHandbookNo());
		// 合同订单号
		searchParam.append("&customerContractNo=");
		searchParam.append(handBook.getCustomerContractNo());		
		// 状态
		searchParam.append("&tabPageStatus=");
		searchParam.append(handBook.getTabPageStatus());
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam.toString());
		
		// 查询一览页面数据
		Page<HandBook> page = handBookService.findList(new Page<HandBook>(request, response),
				handBook);
		// 读取系统路径
		String strUri = request.getContextPath() + Global.getAdminPath();
		// 读取文件生成字符串
		String strHtml = "";
		Map<String, Object> map = new HashedMap();
		map.put("adminUri", strUri);
		map.put("handbooks", page.getList());
		map.put("pageNo", page.getPageNo());
		map.put("pageSize", page.getPageSize());
		strHtml = FreeMarkerTemplateUtils
				.processTemplateIntoString(freemarkerConfiguration.getTemplate("handBook.ftl"), map);
		listMap.put("handbook", strHtml);
		listMap.put("page", page.getHtml());

		// ajax返回结果
		return renderString(response, listMap);
	}
	
	/**
	 * 进入编辑页面
	 * @param handBook
	 * @param model
	 * @return
	 */
	@RequiresPermissions("purchase:handbook:edit")
	@RequestMapping(value = "form")
	public String form(HandBook handBook,RedirectAttributes redirectAttributes, Model model,HttpSession session) {
		
		// 新建判断 若不为null 编辑数据
		if(handBook.getId()!=null){
			// 获取进口料件明细
			HandBook resultImport = handBookService.findImportDetailsByHandBookId(handBook);
			// 获取出口成品明细
			HandBook resultExport = handBookService.findExportDetailsByHandBookId(handBook);
			
			// 设置进口料件明细
			handBook.setImportDetailsList(resultImport.getImportDetailsList());
			// 设置出口成品明细
			handBook.setExportDetailsList(resultExport.getExportDetailsList());
			
			// 设置进口总数
			handBook.setHandbookImportNumber(resultImport.getHandbookImportNumber());
			// 设置进口总值
			handBook.setHandbookImportSum(resultImport.getHandbookImportSum());
			// 设置出口总数
			handBook.setHandbookExportNumber(resultExport.getHandbookExportNumber());
			// 设置出口总值
			handBook.setHandbookExportSum(resultExport.getHandbookExportSum());
			
			// 设置所有订单id
			if(StringUtils.isNotEmpty(resultExport.getCommaIndentId())){
			   handBook.setCommaIndentId(resultExport.getCommaIndentId());
			}
		}

		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("handBook", handBook);
		
		// 返回页面地址
		return "modules/trade/handBookCreate";
	}
	
	/**
     * 进入合同订单选择页面
     * @param orderMateriel
     * @param model
     * @return
     */
    @RequiresPermissions("purchase:handbook:view")
    @RequestMapping(value = "indentSelect")
    public String indentSelect(OrderMateriel orderMateriel, Model model) {
        
    	orderMateriel.setIndentSelectFlg("handbook");
        // 将查询结果赋值mvc model层返回jsp页面
        model.addAttribute("orderMateriel", orderMateriel);
        
        // 返回页面地址
        return "modules/order/indentSelect";
    }
    
	/**
	 * @Title: 画面检索
	 * @Description: 查询页面
	 * @param orderMateriel
	 * @param request
	 * @param response
	 * @param model
	 * @return searchIndentList
	 * @throws ResourceException
	 */
	@RequiresPermissions("purchase:handbook:view")
	@RequestMapping(value = { "searchIndentList" })
	@ResponseBody
	public String searchIndentList(OrderMateriel orderMateriel, HttpServletRequest request, HttpServletResponse response,
			Model model) throws ResourceException {
		Map<Object, Object> listMap = new HashMap<Object, Object>();

		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "indent");

		// 拼接字符串供分页使用
		StringBuilder searchParam = new StringBuilder();
		searchParam.append("&customerIndentNo=");
		searchParam.append(orderMateriel.getCustomerIndentNo());
		searchParam.append("&styleCustomerNo=");
		searchParam.append(orderMateriel.getStyleCustomerNo());
		searchParam.append("&ognizationName=");
		searchParam.append(orderMateriel.getOgnizationName());
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam.toString());
		
		// 查询一览页面数据(不包括状态完了)
		orderMateriel.setIndentStatus(ResourcesUtil.getConfig("Ordef_99"));
		Page<OrderMateriel> page = handBookService.findIndentList(new Page<OrderMateriel>(request, response),orderMateriel);
		String strHtml = "";
		try{
			Map<String, Object>  map = new HashedMap();
			map.put("indentList",page.getList());
			map.put("pageNo",page.getPageNo());
			map.put("pageSize",page.getPageSize());
			strHtml = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfiguration.getTemplate("indentSelect.ftl"), map);
		}
		catch (Exception e) {
            // 记录日志
            logger.error(e.getMessage(), e);
		}
		
		listMap.put("indent", strHtml);
		listMap.put("page", page.getHtml());

		// ajax返回结果
		return renderString(response, listMap);
	}
	
    /**
     * @Title: addExportDetail
     * @Description: 添加出口成品明细
     * @param @param handBook
     * @param @param session
     * @param @return
     * @return String 
     * @throws
     */
   
   @RequiresPermissions("purchase:handbook:edit")
   @RequestMapping(value = "addExportDetail")
   public String addExportDetail(HandBook handBook, HttpServletRequest request, HttpServletResponse response, Model model) {
       try {
       	
    	   // 获得选择的订单信息
    	   HandBook resultExportDetail = handBookService.getExportDetailsByIndentId(handBook.getIndentId());
    	   
    	   if(resultExportDetail!=null){
    		   if(CollectionsUtils.isEmpty(handBook.getExportDetailsList())){
    			   List<HandBook> exportList = new ArrayList<HandBook>();
    			   exportList.add(resultExportDetail);
    			   handBook.setExportDetailsList(exportList);
    		   }else{
    			   handBook.getExportDetailsList().add(resultExportDetail);
    		   }
    		   
    		   // 添加一个订单id
    		   if(StringUtils.isEmpty(handBook.getCommaIndentId())){
    			   handBook.setCommaIndentId(String.valueOf(resultExportDetail.getIndentId()));
    		   }else{
    			   ArrayList<String> oldIndentIdList = new ArrayList<String>(Arrays.asList(handBook.getCommaIndentId().split(",")));
    			   if(!oldIndentIdList.contains(String.valueOf(resultExportDetail.getIndentId()))){
    				   handBook.setCommaIndentId(handBook.getCommaIndentId()+","+String.valueOf(resultExportDetail.getIndentId()));
    			   }
    		   }
    		   
    		   // 计算出口总值和总数
    		   HandBook resultExportTotal = handBookService.exportTotal(handBook.getExportDetailsList());
    		   handBook.setHandbookExportNumber(resultExportTotal.getHandbookExportNumber());
    		   handBook.setHandbookExportSum(resultExportTotal.getHandbookExportSum());
    	   }
           
    	   handBook.setIndentId(null);
	   	    // 将page值赋值给mvc model层返回jsp页面
	   	    model.addAttribute("handBook", handBook);
   	    
           // 返回地址
           return "modules/trade/handBookCreate";
       } catch (Exception e) {
           // 记录日志
           logger.error(e.getMessage(), e);
           // 返回地址
           return "modules/trade/handBookCreate";
       }
       
   }
   
   /**
    * @Title: delExportDetail
    * @Description: 删除出口成品明细
    * @param @param handBook
    * @param @param model
    * @param @param session
    * @param @return
    * @return String 
    * @throws
    */
  
  @RequiresPermissions("purchase:handbook:edit")
  @RequestMapping(value = "delExportDetail")
  public String delExportDetail(HandBook handBook, HttpServletRequest request, HttpServletResponse response, Model model) {
      try {
    	  
    	  // 删除一个订单id
    	  HandBook currentHandBook = handBook.getExportDetailsList().get(handBook.getTrIndex());
    	  if(currentHandBook!=null){
			   ArrayList<String> oldIndentIdList = new ArrayList<String>(Arrays.asList(handBook.getCommaIndentId().split(",")));
			   if(oldIndentIdList.contains(String.valueOf(currentHandBook.getIndentId()))){
				   oldIndentIdList.remove(String.valueOf(currentHandBook.getIndentId()));
				   if(CollectionsUtils.isEmpty(oldIndentIdList)){
					   handBook.setCommaIndentId("");
				   }else{
					   handBook.setCommaIndentId(CollectionsUtils.convertToString(oldIndentIdList, ","));
				   }
			   }

			   if(!CollectionsUtils.isEmpty(handBook.getImportDetailsList())){
				   Iterator<HandBook> it = handBook.getImportDetailsList().iterator();
				   while(it.hasNext()){
					   HandBook itHandBook = it.next();
					   if(currentHandBook.getIndentId().equals(itHandBook.getIndentId())){
						   it.remove();
					   }
				   }
			   }
    	  }
    	  
   		   handBook.getExportDetailsList().remove(handBook.getTrIndex());
   		   

		   // 计算出口总值和总数
		   HandBook resultExportTotal = handBookService.exportTotal(handBook.getExportDetailsList());
		   handBook.setHandbookExportNumber(resultExportTotal.getHandbookExportNumber());
		   handBook.setHandbookExportSum(resultExportTotal.getHandbookExportSum());
		   
		   // 计算进口总值和总数
		   HandBook resultImportTotal = handBookService.importTotal(handBook.getImportDetailsList());
		   handBook.setHandbookImportNumber(resultImportTotal.getHandbookImportNumber());
		   handBook.setHandbookImportSum(resultImportTotal.getHandbookImportSum());
   	   
	   	   // 将page值赋值给mvc model层返回jsp页面
	   	   model.addAttribute("handBook", handBook);
  	    
           // 返回地址
           return "modules/trade/handBookCreate";
      } catch (Exception e) {
          // 记录日志
          logger.error(e.getMessage(), e);
          // 返回地址
          return "modules/trade/handBookCreate";
      }
  }
  
	/**
   * 进入物料选择页面
   * @param handBook
   * @param model
   * @return
   */
  @RequiresPermissions("purchase:handbook:view")
  @RequestMapping(value = "proMaterialSelect")
  public String proMaterialSelect(HandBook handBook, HttpServletRequest request, HttpServletResponse response, Model model) {
      
	    if(StringUtils.isNotEmpty(handBook.getCommaIndentId())){
		    handBook.setReserverMeterialStatus(ResourcesUtil.getConfig("reserver_meterial_ok"));
			// 查询一览页面数据
		    List<HandBook> materialSelectList = handBookService.findMaterialList(handBook);
		    
		    handBook.setMaterialSelectList(materialSelectList);
	    }
	    
	    // 将page值赋值给mvc model层返回jsp页面
	    model.addAttribute("handBook", handBook);

      // 返回页面地址
      return "modules/trade/proMaterialSelect";
  }
  
  /**
   * @Title: addImportDetail
   * @Description: 添加进口料件明细
   * @param @param handBook
   * @param @param session
   * @param @return
   * @return String 
   * @throws
   */
 
 @RequiresPermissions("purchase:handbook:edit")
 @RequestMapping(value = "addImportDetail")
 public String addImportDetail(HandBook handBook, HttpServletRequest request, HttpServletResponse response, Model model) {
     try {
     	
  	   // 获得选择的订单信息
  	   List<HandBook> resultImportDetailList = handBookService.findIxportDetails(handBook.getCommaMaterialReservePurchaseId());
  	   
  	   if(resultImportDetailList!=null){
  		   if(CollectionsUtils.isEmpty(handBook.getImportDetailsList())){
  			   handBook.setImportDetailsList(resultImportDetailList);
  		   }else{
  			   handBook.getImportDetailsList().addAll(resultImportDetailList);
  		   }
  	   }
  	   
	   // 计算进口总值和总数
	   HandBook resultImportTotal = handBookService.importTotal(handBook.getImportDetailsList());
	   handBook.setHandbookImportNumber(resultImportTotal.getHandbookImportNumber());
	   handBook.setHandbookImportSum(resultImportTotal.getHandbookImportSum());
         
   	    // 将page值赋值给mvc model层返回jsp页面
   	    model.addAttribute("handBook", handBook);
 	    
         // 返回地址
         return "modules/trade/handBookCreate";
     } catch (Exception e) {
         // 记录日志
         logger.error(e.getMessage(), e);
         // 返回地址
         return "modules/trade/handBookCreate";
     }
 }
 
 /**
  * @Title: delExportDetail
  * @Description: 删除进口料件明细
  * @param @param handBook
  * @param @param model
  * @param @param session
  * @param @return
  * @return String 
  * @throws
  */

@RequiresPermissions("purchase:handbook:edit")
@RequestMapping(value = "delImportDetail")
public String delImportDetail(HandBook handBook, HttpServletRequest request, HttpServletResponse response, Model model) {
    try {
  	  
      handBook.getImportDetailsList().remove(handBook.getTrIndex());
      
	   // 计算进口总值和总数
	   HandBook resultImportTotal = handBookService.importTotal(handBook.getImportDetailsList());
	   handBook.setHandbookImportNumber(resultImportTotal.getHandbookImportNumber());
	   handBook.setHandbookImportSum(resultImportTotal.getHandbookImportSum());
 	   
	   // 将page值赋值给mvc model层返回jsp页面
   	   model.addAttribute("handBook", handBook);
	    
       // 返回地址
       return "modules/trade/handBookCreate";
    } catch (Exception e) {
        // 记录日志
        logger.error(e.getMessage(), e);
        // 返回地址
        return "modules/trade/handBookCreate";
    }
}

/**
 * 保存信息
 * @param dict
 * @param request
 * @param model
 * @param response
 * @return
 * @throws ResourceException 
 */
@RequiresPermissions("purchase:handbook:edit")
@RequestMapping(value = "save")
@ResponseBody
public String save(HandBook handBook, HttpServletRequest request, Model model, HttpServletResponse response , HttpSession session) throws ResourceException {
	
	// 判断id是否为null （判断新建或修改）
	if(handBook.getId()!=null){
		// 编辑数据
		// 判断数据是否删除
		HandBook handBookNew = get(handBook.getId().toString());
		// 判断数据是否删除
        if(handBookNew==null || BaseEntity.DEL_FLAG_DELETE.equals(handBookNew.getDeleteFlag())){
        	// 返回提示信息
        	return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
        }
		
        // 排他处理
	    if(handBook.getVersion()==get(handBook.getId().toString()).getVersion()){
	    	
	    	// 版本号加1
	    	handBook.setVersion(handBook.getVersion()+1);
	    }else{
	    	
	    	// 返回提示信息
	        return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
	    }
	}

	// 保存基准数据及子项数据
	handBookService.saveHandBook(handBook);
	
	// 保存成功返回提示信息
    return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName( "handBook_create_save_success")));
}

/**
 * 进入查看页面
 * @param handBook
 * @param model
 * @return
 */
@RequiresPermissions("purchase:handbook:view")
@RequestMapping(value = "show")
public String show(HandBook handBook, Model model) {
	
	// 获取进口料件明细
	HandBook resultImport = handBookService.findImportDetailsByHandBookId(handBook);
	// 获取出口成品明细
	HandBook resultExport = handBookService.findExportDetailsByHandBookId(handBook);
	
	// 设置进口料件明细
	handBook.setImportDetailsList(resultImport.getImportDetailsList());
	// 设置出口成品明细
	handBook.setExportDetailsList(resultExport.getExportDetailsList());
	
	// 设置进口总数
	handBook.setHandbookImportNumber(resultImport.getHandbookImportNumber());
	// 设置进口总值
	handBook.setHandbookImportSum(resultImport.getHandbookImportSum());
	// 设置出口总数
	handBook.setHandbookExportNumber(resultExport.getHandbookExportNumber());
	// 设置出口总值
	handBook.setHandbookExportSum(resultExport.getHandbookExportSum());
	
    // 将查询结果赋值mvc model层返回jsp页面
    model.addAttribute("handBook", handBook);
    
    // 返回页面地址
    return "modules/trade/handBookShow";
}

/**
 * 删除信息
 * @param handBook
 * @param response
 * @return
 */
@RequiresPermissions("purchase:handbook:edit")
@RequestMapping(value = "delete")
public String delete(HandBook handBook, HttpServletResponse response) {
	    try {
	    	// 执行逻辑删除方法
	    	handBookService.deleteHandBook(handBook);
        } catch (Exception e) {
            // 记录日志
            logger.error(e.getMessage(), e);
        	// 提示错误信息
            return renderString(response,AjaxDone.error(getText("System_error_please_contact_your_administrator")));
        }
	    
	    // 提示删除成功信息
		return renderString(response,AjaxDone.ok(getText("handBook_show_delete_msg")));
}

/**
 * @Title: resetExportTotalValue
 * @Description: 出口总值，总量
 * @param @param handBook
 * @param @param session
 * @param @return
 * @return String 
 * @throws
 */

@RequiresPermissions("purchase:handbook:edit")
@RequestMapping(value = "resetExport")
public String resetExportTotalValue(HandBook handBook, HttpServletRequest request, HttpServletResponse response, Model model) {
   try {
       HandBook selectHandBook = handBook.getExportDetailsList().get(handBook.getTrIndex());
       
       selectHandBook.setHandbookAmount(handBookService.resetSum(selectHandBook.getHandbookQuantity(), selectHandBook.getHandbookPrice()));

	   // 计算进口总值和总数
	   HandBook resultExportTotal = handBookService.exportTotal(handBook.getExportDetailsList());
	   handBook.setHandbookExportNumber(resultExportTotal.getHandbookExportNumber());
	   handBook.setHandbookExportSum(resultExportTotal.getHandbookExportSum());
       
 	    // 将page值赋值给mvc model层返回jsp页面
 	    model.addAttribute("handBook", handBook);
	    
       // 返回地址
       return "modules/trade/handBookCreate";
   } catch (Exception e) {
       // 记录日志
       logger.error(e.getMessage(), e);
       // 返回地址
       return "modules/trade/handBookCreate";
   }
}

/**
 * @Title: addImportDetail
 * @Description: 添加进口料件明细
 * @param @param handBook
 * @param @param session
 * @param @return
 * @return String 
 * @throws
 */

@RequiresPermissions("purchase:handbook:edit")
@RequestMapping(value = "resetImport")
public String resetImportTotalValue(HandBook handBook, HttpServletRequest request, HttpServletResponse response, Model model) {
   try {
	   
       HandBook selectHandBook = handBook.getImportDetailsList().get(handBook.getTrIndex());
       
       selectHandBook.setHandbookAmount(handBookService.resetSum(selectHandBook.getHandbookQuantity(), selectHandBook.getHandbookPrice()));
   		   
	   // 计算进口总值和总数
	   HandBook resultImportTotal = handBookService.importTotal(handBook.getImportDetailsList());
	   handBook.setHandbookImportNumber(resultImportTotal.getHandbookImportNumber());
	   handBook.setHandbookImportSum(resultImportTotal.getHandbookImportSum());
       
 	    // 将page值赋值给mvc model层返回jsp页面
 	    model.addAttribute("handBook", handBook);
	    
       // 返回地址
       return "modules/trade/handBookCreate";
   } catch (Exception e) {
       // 记录日志
       logger.error(e.getMessage(), e);
       // 返回地址
       return "modules/trade/handBookCreate";
   }
}

/**
 * 审核页面
 * @param handBook
 * @param model
 * @return
 */
@RequiresPermissions("purchase:handbook:audit")
@RequestMapping(value = "audit")
public String audit(HandBook handBook,RedirectAttributes redirectAttributes, Model model,HttpSession session) {
	
	// 履历一览取得
	AuditInfo auditInfo = new AuditInfo();
	// 样品生产id
	auditInfo.setAuditRelateId(handBook.getId());
	// 阶段（样品)
	auditInfo.setAuditPhaseCd(ResourcesUtil.getConfig("audit_phase_handbook"));
	AuditInfo resultInfo = handBookService.findAuditInfo(auditInfo);
	
	// 待审核状态可以审核
	if(resultInfo.getAuditStatus()==0){
		String strWaitAccept = ResourcesUtil.getConfig("reserver_meterial_wait_accept");
		if(!handBook.getHandbookAuditStatus().equals(strWaitAccept)){
			resultInfo.setAuditStatus(1L);
		}
	}
	
	// 样品生产id
	resultInfo.setAuditRelateId(handBook.getId());
	// 样品需求单号
	resultInfo.setAuditRelateNo(handBook.getHandbookNo());
	// 阶段
	resultInfo.setAuditPhaseCd(ResourcesUtil.getConfig("audit_phase_handbook"));
	// 核料状态
	resultInfo.setVersion(handBook.getVersion());
	
	// 将实体类值赋给mvc model层返回jsp页面
	model.addAttribute("auditInfo", resultInfo);
	
	// 返回页面地址
	return "modules/order/auditInfo";
}

/**
 * 保存履历信息
 * @param auditInfo
 * @param request
 * @param model
 * @param response
 * @return
 * @throws ResourceException 
 */
@RequiresPermissions("specimen:production:edit")
@RequestMapping(value = "saveAudit")
@ResponseBody
public String saveAudit(AuditInfo auditInfo,HttpServletRequest request, Model model, HttpServletResponse response , HttpSession session) throws ResourceException {
	
	// 判断数据是否删除
	HandBook newHandBook=get(Long.toString(auditInfo.getAuditRelateId()));
	
	// 判断数据是否删除
	if(newHandBook==null || BaseEntity.DEL_FLAG_DELETE.equals(newHandBook.getDeleteFlag())){
		// 返回提示信息
		return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
	}
	
    // 审核结果已经通过,返回错误提示信息
	AuditInfo pAuditResult = new AuditInfo();
	pAuditResult.setAuditPhaseCd(auditInfo.getAuditPhaseCd());
	pAuditResult.setAuditRelateId(auditInfo.getAuditRelateId());
	if(handBookService.getAuditResult(pAuditResult)>0){
    	// 返回提示信息
        return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
	}
	
	// 排他
	if(auditInfo.getVersion()==get(Long.toString(auditInfo.getAuditRelateId())).getVersion()){
		// 版本号加1
		auditInfo.setVersion(auditInfo.getVersion()+1);
    	
    }else{	
    	// 返回提示信息
        return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
    }
	
    // 设置采购手册状态
	if(auditInfo.getAuditResult()==1){
	  	auditInfo.setSampleRequestStatus(ResourcesUtil.getConfig("reserver_meterial_ok"));
	}else{
	   	auditInfo.setSampleRequestStatus(ResourcesUtil.getConfig("reserver_meterial_no"));
	}
	
    // 保存样品数据
	handBookService.saveAuditInfo(auditInfo);
			
	// 保存成功返回提示信息
    return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName( "audit_ok_msg")));
}
}
